<template>
  <div style="width: 640px; position:relative;">
    <div class="upload">
      <!-- <el-upload :action="url"
        :show-file-list="false" 
        :multiple="true" 
        :data="postData" 
        :accept="accept_type"
        :name="fileKey" 
        :disabled = "gid == 0"
        :auto-upload = "autoUpload"
        :on-progress="progress" 
        :on-change="onChange" 
        :on-success="onSuccess" 
        style="margin-top: 0px; position:absolute; top: 10px;"
      > -->
      <el-upload :action="url"
        :show-file-list="false" 
        :multiple="true" 
        :data="postData" 
        :accept="accept_type"
        :name="fileKey" 
        :disabled = "gid == 0"
        :auto-upload = "autoUpload"
        :on-progress="onProgress"
        :on-change="onChange" 
        :on-success="onSuccess" 
        style="margin-top: -10px; position:absolute; top: 10px;"
      >
        <el-button icon="el-icon-upload" :disabled="gid == 0" type="primary" size="small" style="height: 32px;">选择文件上传</el-button>
      </el-upload>
    </div>
    <div class="upload-list">
      <div class="upload_info" v-for="item in files" :key="item.id">
        <div class="file-icon"><svg-icon icon-class="PDF"/></div>
        <div class="file-name">{{ item.oname }}</div>
        <div class="file-progress">
          <el-progress :text-inside="true" :stroke-width="18" status="success" :percentage="item.percent"></el-progress>
        </div>
        <div class="file-status">
          <div v-if="item.taskId == 0">
            <span v-if="item.status == 'success'"><span class="el-icon-success" style="color:green; margin-right:6px;" />准备转换</span>
            <span v-else>
              上传中...
            </span>
          </div>
          <div v-else>
            <span v-if="item.transStatus == 'Finished'"><span class="el-icon-success" style="color:green; margin-right:6px;" />转换完成</span>
            <span v-else>
              转换中... 
            </span>                
          </div>
        </div>
        <div class="file-btn">
          <el-button type="danger" size="mini" icon="el-icon-delete" style="padding:3px;" @click="removeFailFile(item.id)" circle></el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { pdf2png, checkTask } from '@/api/report'
import { saveGroupFile } from '@/api/group'
// import { clearTimeout } from 'timers';
export default {
  name: 'FileUploader',
  data() {
    return {
      autoUpload: true,
      files : [],
      fileKey: 'file',
      postData: {gid: 0},
      compDis: false,
      upFileCount: 0
    }
  },
  computed: {
    // ...mapGetters(['gid'])
  },
  watch: {
    files: function (nv, ov) {
    },
    gid: function(nv, ov) {
      this.postData.gid = nv
    },
    upFileCount: function(nv, ov) {
      // this.$emit('bubbleFresh', nv)
    }
  },
  props: ['url', 'accept_type','gid'],
  mounted() {
    // console.log('url:' + this.url)
  },
  methods: {
    onSuccess(response, file, fileList) {
      // 更新
      if (response.code === 0) {
        let ossName = response.url
        let pageDir = 'pages'
        // 存储
        let uploadFile = this.getUploadFile(file.uid)
        uploadFile.name = ossName
        // 开始执行拆分操作
        pdf2png(ossName, pageDir + "/").then(res => {
          // 启动定时任务, 检查
          uploadFile.transProgress = 0
          uploadFile.taskId = res.infor.task_id
          // 开启检查
          this.check2png(uploadFile)
        })
        // this.$message.success(file.name + '上传成功')
        // 触发更新时间
        // this.$emit('bubblefresh')
      } else {
        this.$message.error('上传失败, 请稍后重试,')
        this.removeFailFile(file.uid)
      }
    },
    onProgress(event, file, fileList) {
      let uploadfile = this.getUploadFile(file.uid)
      uploadfile.percent = file.percentage / 2
    },
    onChange(file, fileList) {
      fileList.forEach(file => {
        let findIt = false;
        this.files.forEach(ofile => {
          if (ofile.id == file.uid) {
            findIt = true;
            // ofile.percent = file.percentage
            ofile.status = file.status
          }
        })
        // 检查是否存在该文件
        if (!findIt) {
          this.files.push({
            id: file.uid,
            status: file.status,
            percent: file.percentage / 2,
            transProgress: 0,
            loopId: 0,
            taskId: 0,
            page_count: 0,
            oname: file.name,
            name: '',
            transStatus: ''
          })
        }
      });
    },
    // 私有工具函数
    // 找到该文件
    getUploadFile(id) {
      let file = undefined
      for (let i = 0; i < this.files.length; i++) {
        if (this.files[i].id == id) {
          file = this.files[i]
          break
        }
      }
      return file
    },
    removeFailFile(fid) {
      // let file = this.getUploadFile(fid)
      for (let i = 0; i < this.files.length; i++) {
        if (this.files[i].id == fid) {
          clearTimeout(this.files[i].loopId)
          this.files[i].loopId = 0
          this.files[i].taskId = 0
          this.files.splice(i, 1)
        }
      }
    },
    // 检查是否已经完成分解
    check2png(uploadFile) {
      // 获取sid
      uploadFile.loopId = setInterval(() => {
        // 验证文件是否拆分完成
        if (uploadFile.taskId) {
          checkTask(uploadFile.taskId).then(res => {
            switch (res.infor.status) {
              case 'Finished':
                uploadFile.pageCount = res.infor.page_count
                uploadFile.percent = 200
                uploadFile.transStatus = res.infor.status
                this.checkTaskFin(uploadFile, 1);
                break;
              case 'Failed':
                this.checkTaskFin(uploadFile, 0);
                break;
            }
          })
        }
      }, 1000)
    },
    checkTaskFin(uploadFile, status) {
      if (status == 1) {
        this.$message.success('文档 ['+ uploadFile.oname+"] 转换成功 !!!");

        // 添加到群文件中
        saveGroupFile(this.gid, uploadFile.oname, uploadFile.name, uploadFile.pageCount).then(res => {
          this.upFileCount += 1
          // 触发更新时间
          this.$emit('bubblefresh', this.upFileCount)
        })
      } else {
        this.$message.error('文档 ['+ uploadFile.oname+"] 转换失败, 请重新分解 !!!");
      }
      // 一切都结束了
      clearInterval(uploadFile.loopId);
      // 清除循环的ID
      uploadFile.loopId = 0;
    }
  }
}
</script>
<style lang="less" scoped>
  .upload {
    width: 120px;
    height: 32px;
    display: inline-block;
  }
  .upload-list {
    display: inline-block;
    box-sizing: border-box;
    padding-top: 0px;
    .upload_info {
      width: 510px;
      position: relative;
      height: 32px;
      background-color: #FBFBFB;
      border-radius: 3px;
      box-sizing: border-box;
      padding-left: 5px;
      // border: 1px solid #CCCCCC;
      .file-icon {
        width: 14px;
        position: absolute;
        top: 8px;
      }
      .file-name {
        width:200px;
        overflow: hidden;
        text-overflow:ellipsis;
        white-space: nowrap;
        position: absolute;
        left: 25px;
        top: 10px;
        font-size: 14px;
      }

      .file-progress {
        width: 150px;
        position: absolute;
        left: 250px;
        top: 7px;
      }

      .file-status {
        width: 80px;
        position: absolute;
        left: 422px;
        top: 8px;
        font-size: 14px;
      }

      .file-btn {
        position: absolute;
        left: 540px;
        top: 4px;
      }
    }
  }
</style>


